import React from 'react';
import {
  Row,
  Col,
  Table,
  Icon,
  DatePicker,
  Select,
  message
} from 'antd';
import axios from 'axios';
import OrderList from './RentOrderList';
import intercept from '../../../utils/intercept';
import { config } from 'utils';
import { Input } from 'antd';
import { Link } from 'dva/router';
import '../../CustomService/OrderInfo/OrderInfo.less';
import format from './format';
const { RangePicker } = DatePicker;
const Option = Select.Option;
export default class OrderInfo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: [],
      loading: false,
      pagination: {
        current: 1,
        pageSize: 10
      },
      onChange: this.onChange,
      keyword: ''
    };
  };

  componentDidMount() {
    this.getOrderInfo();
  };

  search(value) {
    this.setState({ keyword: value });
    this.getOrderInfo({ keyword: value });
  }

  onChange = (pagination, filters, sorter) => {
    this.getOrderInfo({
      sortField: sorter.field,
      sortOrder: sorter.order,
      page: pagination.current,
      keyword: this.state.keyword,
      ...filters
    });
  };

  getOrderInfo = (params = {}) => {
    this.startDate = this.startDate == undefined ? '' : this.startDate;
    this.endDate = this.endDate == undefined ? '' : this.endDate;
    this.orderStatus = this.orderStatus == undefined ? '' : this.orderStatus;
    const token = sessionStorage.getItem("token");
    this.setState({ loading: true });
    var keyword = typeof (params.keyword) === "undefined"
      ? ''
      : params.keyword;
    axios
      .get(`${config.api}Rental/GetOrders?page=${params.page}&pageSize=${this.state.pagination.pageSize}&keyword=${keyword}&start=${this.startDate}&end=${this.endDate}&orderStatus=${this.orderStatus}`, { headers: { Authorization: 'Bearer ' + token } })
      .then((data) => {
        const pagination = {
          ...this.state.pagination
        };
        if (data.data.result) {
          data.data.pageList.collections.forEach(function (item, index) {
            item.rentalTime = format.format(item.rentalTime);
          })
        }
        pagination.total = data.data.pageList.totalRows;
        pagination.current = params.page;
        this.setState({ loading: false, dataSource: data.data.pageList.collections, pagination, totalMoney: data.data.totalMoney, totalPerson: data.data.totalPerson });

      }).catch(err => {
        intercept;
      });
  };

  // 日期选择器触发函数
  stateOnChange = (date, dateString) => {
    this.startDate = dateString[0];
    this.endDate = dateString[1];
    this.getOrderInfo()
  }
  // Select选择器触发函数
  handleChange = (value) => {
    this.orderStatus = value;
    this.getOrderInfo()
  }
  // 撤销按钮操作
  repeal = (id) => {
    const token = sessionStorage.getItem("token");
    axios.post(`${config.api}Rental/CancleRentalOrder`, { orderid: id }, { headers: { Authorization: 'Bearer ' + token } }).then(
      data => {
        if (data.data.result) {
          message.success("撤销成功")
          this.getOrderInfo();
        } else {
          message.warning(data.data.errorMessage)
        }
      }
    ).catch(err => {
      intercept;
    })
  }

  orderState(val) {
    if (val == 0) {
      return '待支付'
    } else if (val == 1) {
      return '已支付'
    } else if (val == 2) {
      return '已取消'
    } else if (val == 3) {
      return '已派车'
    } else if (val == 4) {
      return '已检票'
    } else if (val == 5) {
      return '已申请退款'
    } else if (val == 6) {
      return '退款成功'
    } else if (val == 7) {
      return '无'
    } else if (val == 8) {
      return '无'
    } else if (val == 9) {
      return '无'
    }
  }


  render() {
    const Search = Input.Search;
    const statusstr = ['待支付', '已支付', '已取消', '已打印', '客服申请退款', '客服申请退款成功', '超时支付申请退款', '超时支付退款成功', '用户申请退款', '退款成功'];
    const columns = [
      {
        title: '订单号',
        dataIndex: 'orderCode',
        width: 150
      }, {
        title: '线路名称',
        dataIndex: 'carLineName',
        width: 150                                                          
      },{
        title: '用户手机',
        dataIndex: 'userPhone',
        width: 120
      }, {
        title: '订单人数',
        dataIndex: 'passengerAccount',
        width: 50
      }, {
        title: '票价/总金额',
        dataIndex: 'originalTotalPrice',
        // sorter: true,
        width: 60
      }, {
        title: '约租时间',
        dataIndex: 'rentalTime',
        width: 160
      }, {
        title: '订单归属单位',
        dataIndex: 'companyCode',
        // sorter: true,
        width: 80
      }, {
        title: '订单状态',
        // dataIndex: 'orderStatus',
        width: 100,
        render: (text, record) => {
          return (<span>{this.orderState(record.orderStatus)}</span>)
        }
      }, {
        title: '操作',
        width: 150,
        key: 'action',
        render: (text, record) => {
          return (
            <span>
              <Link style={{ color: record.isCommented ? '#108ee9' : 'gray', marginRight: '5px' }} href={record.isCommented ? `/orderinfo/CreateRefund_Qcp?sn=${record.id}` : '#'}>{record.isCommented ? '申请退款' : '已申请退款'}</Link>
              | <span style={{ color: record.orderStatus == 1 && record.orderChannel == "电话订单" ? "#108ee9" : 'gray', cursor: record.orderStatus == 1 && record.orderChannel == "电话订单" ? "Pointer" : 'Default', marginLeft: '3px' }} onClick={record.orderStatus == 1 && record.orderChannel == "电话订单" ? () => this.repeal(record.id) : ''}>撤销</span>
            </span>
          )
        }
      }
    ];
    const className = "components-table-demo-nested";
    const expandedRowRender = record => <OrderList id={record.id} />; //<p>{record.orderCode}</p>;
    const scroll = {
      y: 600
    };

    return (
      <div className="orderinfo">
        <Row gutter={8} style={{
          marginTop: '20px'
        }}>

          <div
            style={{
              textAlign: 'center',
              marginTop: 10
            }}>
            <div className="statOrder" style={{
              display: 'inline-block',
            }}>
              <p>总金额(元)：<span>{this.state.totalMoney}</span></p>
              <p>总人次(人)：<span>{this.state.totalPerson}</span></p>
            </div>
            <RangePicker onChange={this.stateOnChange} />
            <Select defaultValue="null" style={{ width: 100, marginLeft: '10px', textAlign: 'center' }} onChange={this.handleChange}>
              <Option value="null">全部</Option>
              <Option value="1">已支付</Option>
              <Option value="2">已取消</Option>
              <Option value="3">已派车</Option>
              <Option value="5">已申请退款</Option>
            </Select>
          </div>
          <Col span={24}>
            <div
              style={{
                textAlign: 'center',
                margin: 10
              }}>

              <Search
                placeholder="请输入订单号"
                style={{
                  width: 600
                }}
                onSearch={value => this.search(value)} />

            </div>
            <Table
              rowKey={record => record.id}
              {...this.state}
              expandedRowRender={expandedRowRender}
              bordered={true}
              className={className}
              columns={columns}
              scroll={scroll} />
          </Col>
        </Row>
      </div>
    )
  }
}
